type ListType = {
  id: number;
  task: string;
  isDone: boolean;
};
const initState = {
  list: JSON.parse(localStorage.getItem('todo-list') || '[]') as ListType[],
  type: (localStorage.getItem('todo-type') || 'all') as todoFliterType,
};
export type todoFliterType = 'all' | 'active' | 'completed';
export type todoType =
  | { type: 'todo/delById'; payload: number }
  | { type: 'todo/checkById'; payload: number }
  | { type: 'todo/changeType'; payload: todoFliterType }
  | { type: 'todo/addTask'; payload: string }
  | { type: 'todo/AllCheck'; payload: boolean }
  | { type: 'todo/clearCompleted' };
export default function todoReducer(
  state = initState,
  action: todoType
): typeof initState {
  const { list } = state;
  switch (action.type) {
    case 'todo/delById':
      return {
        ...state,
        list: list.filter((item) => item.id !== action.payload),
      };
    case 'todo/checkById':
      return {
        ...state,
        list: list.map((item) => ({
          ...item,
          isDone: item.id === action.payload ? !item.isDone : item.isDone,
        })),
      };
    case 'todo/changeType':
      return {
        ...state,
        type: action.payload,
      };
    case 'todo/clearCompleted':
      return {
        ...state,
        list: list.filter((item) => !item.isDone),
      };
    case 'todo/addTask':
      return {
        ...state,
        list: [
          { task: action.payload, isDone: false, id: Date.now() },
          ...list,
        ],
      };
    case 'todo/AllCheck':
      return {
        ...state,
        list: list.map((item) => ({ ...item, isDone: action.payload })),
      };
    default:
      return state;
  }
}
